<template>
  <div class="popup-container">
    <div class="popup-title">
      图斑属性查看
      <div class="popup-toolbar">
        <el-button size="mini" @click="showEditPage" type="text">编辑</el-button>
      </div>
    </div>
    <div class="popup-select">
      <el-select v-model="layerValue" placeholder="请选择" size="mini" style="width: 100%;" @change="layerSelectHandler">
        <el-option v-for="item in layerSelect" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </div>
    <div class="popup-content">
      <div class="popup-field" v-for="item in Object.keys(showFields)">
        <div class="popup-field-key">{{ item }}</div>
        <template v-if="(item === '调查图片远景') && srcList.length !== 0">
          <el-image style="width: 80px; height: 80px;border:1px solid white;" :src="srcList[0]"
            :preview-src-list="getImgList(0)">
          </el-image>
        </template>
        <template v-else-if="(item === '调查图片近景') && srcList.length !== 0">
          <el-image style="width: 80px; height: 80px;border:1px solid white;" :src="srcList[1]"
            :preview-src-list="getImgList(1)">
          </el-image>
        </template>
        <template v-else-if="(item === '调查图片井内') && srcList.length !== 0">
          <el-image style="width: 80px; height: 80px;border:1px solid white;" :src="srcList[2]"
            :preview-src-list="getImgList(2)">
          </el-image>
        </template>
        <template v-else-if="(item === '调查图片') && srcList.length === 0">
          <div class="popup-field-value">无调查图片</div>
        </template>
        <template v-else>
          <div class="popup-field-value">{{ showFields[item] + "" }}</div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { EventBus } from "../../../utils/bus";
import PiplineProjectController from '../../../api/Controller/PiplineProjectController';
import Vue from 'vue';
import { mapMutations, mapGetters } from 'vuex';
import config from '@/core/config/'

export default {
  name: "Popup",
  data() {
    return {
      //实例对象
      fApi: {},
      //表单数据
      value: {},
      //表单生成规则
      rule: [
        {
          type: 'input',
          field: 'goods_name',
          title: '商品名称'
        },
        {
          type: 'datePicker',
          field: 'created_at',
          title: '创建时间'
        }
      ],
      //组件参数配置
      option: {
        //表单提交事件
        onSubmit: function (formData) {
          console.log("formData", JSON.stringify(formData))
        }
      },
      layerSelect: [{

      }],
      layerValue: null,
      projectConfig: null,
      showObject: {},// 这个记录的是显示的那个对象
      showFields: {},// 这个是具体需要显示的属性
      layerFields: {},
      imageList: [
        { url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' },
        { url: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' },
        { url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg' },
      ],
      url: "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
      srcList: ["https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg", "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg", "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg"]
    };
  },
  props: ["obj"],
  mounted() {
    let that = this
    this.readyData(this.obj)
  },
  beforeDestroy() {
    console.log("弹窗被销毁")
  },
  computed: {
    ...mapGetters(["getVectorLayerKeys", "getCurrentProjectConfig"])
  },
  methods: {
    getImgList(index) {
      let arr = []
      let i = 0;
      for (i; i < this.srcList.length; i++) {
        arr.push(this.srcList[i + index])
        if (i + index >= this.srcList.length - 1) {
          index = 0 - (i + 1);
        }
      }
      return arr;
    },
    readyData(data) {
      let that = this
      let { properties,
        projectConfig } = data;
      console.log("项目配置", projectConfig)
      this.projectConfig = projectConfig;
      this.layerSelect = [];
      let layerHash = {};//图层id与图层名称hash
      let layerPrimaryKeyHash = {};//图层id与图层属性主键hash
      projectConfig.data.forEach((item, index) => {
        layerHash[item.layerId] = item.layerName;
        layerPrimaryKeyHash[item.layerId] = item.primaryKey;
      })
      let projectId = projectConfig.projectId;//项目id
      Object.keys(properties).forEach((item, index) => {
        that.layerSelect.push({
          label: layerHash[item.split('-')[0]] + '    ' + item.split('-')[1],
          value: projectId + "-" + item.split('-')[0] + "-" + properties[item].properties[[layerPrimaryKeyHash[item.split('-')[0]]]]
        })
      })

      this.$nextTick(() => {
        that.layerValue = that.layerSelect[0].value
      })

      let firstLayerId = that.layerSelect[0].value.split('-')[1];
      let firstBlockId = that.layerSelect[0].value.split('-')[2];

      // 拼接layerFields
      that.layerFields = {};
      projectConfig.data.forEach((item, index) => {
        let temp = {};
        item.layerFields.forEach((_item, _index) => {
          temp[_item.name] = _item.displayName;
        })
        that.layerFields[item.layerId] = temp;
      })

      // 默认将第一个图形查询出来
      this.searchLayerData({
        projectId: projectId,
        layerId: firstLayerId,
        dataId: firstBlockId
      })
    },
    searchLayerData(data) {
      let that = this;
      let { projectId, layerId, dataId } = data;
      console.log("查询图层数据xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", data)
      this.showObject = data;
      let params = {
        projectId: projectId,
        layerId: layerId,
        dataId: dataId,
      };

      let popupFields = [];
      let suportImage = false
      this.projectConfig.data.forEach((item, index) => {
        if (layerId === item.layerId) {
          popupFields = item.popupFields;
          suportImage = item.supportImage === 1;
        }
      });

      if (popupFields === undefined || popupFields === null || popupFields.length === 0) {
        this.$message.warning("当前图层:" + layerId + "，没有配置Popup字段")
      }

      this.showFields = {};
      // console.log("111111111", this.showFields)
      PiplineProjectController.viewLayerData(this, params, null, { showMask: false }).then((res) => {
        if (res.success) {
          if (res.data !== null) {
            let allFields = res.data;
            console.log("展示查询矢量数据", res);
            popupFields.forEach((item, index) => {
              // console.log("需要展示的字段名", item)
              Vue.set(that.showFields, that.layerFields[layerId][item], allFields[item] === undefined ? '' : allFields[item])
            })
            // 如果字段里有relate_images字段，加进来
            if (suportImage) {
              // 作为图片预览使用
              // Vue.set(that.showFields, '调查图片', allFields['relate_images'] === undefined ? '' : allFields['relate_images'])
              // that.srcList = [];//allFields['relate_images'];
              // if (allFields['relate_images'] !== undefined && allFields['relate_images'] !== null && allFields['relate_images'].length !== 0) {
              //   allFields['relate_images'].forEach((item, index) => {
              //     that.srcList[index] = config.baseUrl + item.slice(1);
              //   })
              // }
              that.srcList = [];//allFields['relate_images'];
              if (allFields['image1'] !== undefined && allFields['image1'] !== null && allFields['image1'] !== '') {
                Vue.set(that.showFields, '调查图片远景', '远景')
                // that.srcList[0] = config.baseUrl + allFields['image1'].slice(1);
                that.srcList.push(config.baseUrl + allFields['image1'].slice(1));
              }
              if (allFields['image2'] !== undefined && allFields['image2'] !== null && allFields['image2'] !== '') {
                Vue.set(that.showFields, '调查图片近景', '近景')
                // that.srcList[1] = config.baseUrl + allFields['image2'].slice(1);
                that.srcList.push(config.baseUrl + allFields['image2'].slice(1));
              }
              if (allFields['image3'] !== undefined && allFields['image3'] !== null && allFields['image3'] !== '') {
                Vue.set(that.showFields, '调查图片井内', '井内')
                // that.srcList[2] = config.baseUrl + allFields['image3'].slice(1);
                that.srcList.push(config.baseUrl + allFields['image2'].slice(1));
              }
              if (that.srcList.length === 0) {
                Vue.set(that.showFields, '调查图片', '无调查图片')
              }

              console.log("查看图片路径", that.srcList)
              console.log("查看图片路径2", allFields)
              console.log("查看图片路径3", that.showFields)
            }

            //   console.log("查看图片路径", allFields['relate_images'])
          } else {
            that.$message.error("没有查询到数据，", params)
          }
        } else {
          that.$message.error("查询异常：", res.errorMessage)
        }
      }).catch(err => {
        console.log("err:", err)
      })
    },
    openD(geom) {
      // EventBus.$emit("detailVUE", geom);
    },
    testA(args) {
      console.log("asdasd12321", args)
    },
    layerSelectHandler(e) {
      let projectId = e.split('-')[0];
      let layerId = e.split('-')[1];
      let dataId = e.split('-')[2];

      this.searchLayerData({
        projectId: projectId,
        layerId: layerId,
        dataId: dataId
      })
    },
    showEditPage() {
      EventBus.$emit("showEditPage", this.showObject);
    }
  },
};
</script>

<style lang="scss" scoped>
.popup-container {
  position: relative;
  max-height: 400px;
  overflow: auto;
  color: black;
}

.popup-title {
  width: 100%;
  height: 20px;
  font-size: 18px;
  font-weight: bold;
  height: 30px;

  // border: 1px solid rgb(32, 45, 121);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-select {
  width: 100%;
  height: 40px;
  text-align: center;

  // border: 1px solid red;
}

.popup-content {
  width: 100%;
  max-height: 300px;
  padding: 10px;
  font-size: 14px;
  overflow: scroll;

  .popup-field {
    display: flex;

    .popup-field-key {
      width: 130px;
    }

    .popup-field-value {
      width: 260px;
    }
  }

  .popup-field:not(:first-child) {
    margin-top: 10px;
  }
}

.popup-toolbar {
  position: absolute;
  right: 10px;
  text-align: right;
}
</style>
